package com.huluobo.a2204parkdemo.notice

import androidx.lifecycle.MutableLiveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.huluobo.base.bean.NoticeBeanItem
import com.huluobo.base.mvvm.BaseViewModel
import com.huluobo.base.net.ApiService
import com.huluobo.base.net.getServiceToken
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import okhttp3.RequestBody
import javax.inject.Inject

/**
 *  Created by LC on 2024/8/30.
 */
@HiltViewModel
class NoticeViewModel @Inject constructor(
    val apiService: ApiService
) : BaseViewModel() {
    val getAllNoticeSuccess by lazy { MutableLiveData<String>() }
    fun getAllNotice(body: RequestBody) {
        executeNetRequest(
            { apiService.getAllNotice(body) },
            getAllNoticeSuccess::postValue
        )
    }

    val addNoticeSuccess by lazy { MutableLiveData<String>() }
    fun addNotice(body: RequestBody) {
        executeNetRequest(
            { apiService.addNotice(body) },
            addNoticeSuccess::postValue
        )
    }

    fun getNewPagingData(): Flow<PagingData<NoticeBeanItem>> {
        return Repo.getPagingData()
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val apiService = getServiceToken<ApiService>()

    fun getPagingData(): Flow<PagingData<NoticeBeanItem>> {
        return Pager(
            config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = {
                NoticePagingSource(apiService)
            }
        ).flow
    }
}